<template>
  <div class="app-container">
    <!-- 操作 -->
    <el-row style="margin-bottom: 10px;">
      <!-- 搜索 -->
      <div v-if="showSearch" class="filter-container" style="display: inline-block">
        <el-form :inline="true" :model="listQuery" class="form-inline">
          <el-form-item label="">
            <el-input v-model="listQuery.title" placeholder="标题" clearable size="small"/>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="listQuery.cid" placeholder="文章分类" default-first-option size="small">
              <el-option label="全部分类" value="-1"/>
              <el-option v-for="item in allCategory" :key="item.id" :label="item.html + item.title" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select
              v-model="listQuery.isDel"
              placeholder="是否删除"
              default-first-option
              clearable
              size="small">
              <el-option label="全部" value="-1"/>
              <el-option label="回收站" value="1"/>
              <el-option label="正常" value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="listQuery.createTime" placeholder="创建时间" default-first-option size="small">
              <el-option label="全部" value="all"/>
              <el-option label="昨天" value="yesterday"/>
              <el-option label="今天" value="today"/>
              <el-option label="本周" value="week"/>
              <el-option label="本月" value="month"/>
              <el-option label="本季度" value="quarter"/>
              <el-option label="本年" value="year"/>
              <el-option label="自定义" value="custom"/>
            </el-select>
          </el-form-item>
          <el-form-item v-if="listQuery.createTime === 'custom'" label="">
            <el-date-picker
              v-model="dateTime"
              :picker-options="pickerOptions"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              align="right"
              clearable
              size="small"/>
          </el-form-item>
          <el-form-item>
            <el-button v-waves type="primary" icon="el-icon-search" size="small" @click="handleFilter">搜索
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              v-waves
              type="warning"
              icon="el-icon-refresh"
              size="small"
              @click="handleFilterClear">重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-col :xs="24" :sm="24" :lg="24">
        <el-tooltip content="刷新" placement="top">
          <el-button v-waves type="warning" icon="el-icon-refresh" circle @click="handleFilterClear"/>
        </el-tooltip>
        <el-tooltip content="增加" placement="top">
          <el-button v-waves type="success" icon="el-icon-plus" circle @click="handleAdd"/>
        </el-tooltip>
        <el-tooltip content="搜索" placement="top">
          <el-button v-waves type="primary" icon="el-icon-search" circle @click="showSearch = !showSearch"/>
        </el-tooltip>
        <el-tooltip content="删除" placement="top">
          <el-button
            v-waves
            :loading="deleting"
            :disabled="buttonDisabled"
            type="danger"
            icon="el-icon-delete"
            circle
            @click="handleDeleteAll"/>
        </el-tooltip>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      :fit="true"
      border
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="ID" align="center" width="60" prop="id" sortable="custom" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文章标题" min-width="180px" fixed>
        <template slot-scope="scope">
          <span class="link-type">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" width="120px">
        <template slot-scope="scope">
          <span>{{ scope.row.cateName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="访问量" min-width="80px">
        <template slot-scope="scope">
          <span>{{ scope.row.visit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="60px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核" width="100px" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleModifyStatus(scope.row,scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="回收站" width="100px" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isDel"
            :active-value="1"
            :inactive-value="0"
            @change="handleModifyDelStatus(scope.row,scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180px">
        <template slot-scope="scope">
          <span>{{ scope.row.addTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="60px"
        class-name="small-padding fixed-width"
        fixed="right">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button
              v-waves
              type="primary"
              icon="el-icon-edit-outline"
              circle
              @click="handleUpdate(scope.$index,scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-show="total>0"
        :current-page="listQuery.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.psize"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @closed="initTemp">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="width: 100%; height: 50vh;overflow-y: scroll;">
        <el-form-item label="文章分类" prop="cid">
          <el-select v-model="temp.cid" class="filter-item" placeholder="请选择">
            <el-option v-for="item in allCategory" :key="item.id" :label="item.html + item.title" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="temp.title" clearable/>
        </el-form-item>
        <el-form-item label="短标题" prop="stitle">
          <el-input v-model="temp.stitle" clearable/>
        </el-form-item>
        <el-form-item label="关键字" prop="tags">
          <el-select
            v-model="tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="输入关键词"
            value-key="id"
            class="keyword">
            <el-option
              v-for="item in tagList"
              :key="item.id"
              :label="item.title"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="摘要" prop="synopsis">
          <el-input
            v-model="temp.synopsis"
            type="textarea"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="缩略图" prop="image">
          <UploadImage v-model="temp.image" :config="config"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="temp.sort" clearable/>
        </el-form-item>
        <el-form-item label="原文链接" prop="url">
          <el-input v-model="temp.url" clearable/>
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="temp.source" clearable/>
        </el-form-item>
        <el-form-item label="显示日期" prop="displayTime">
          <el-date-picker
            v-model="displayTime"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="timestamp"/>
        </el-form-item>
        <el-form-item label="是否审核" class="el-col-12">
          <el-switch
            v-model="temp.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="是否删除" class="el-col-12">
          <el-switch
            v-model="temp.isDel"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="是否热门" class="el-col-12">
          <el-switch
            v-model="temp.isHot"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="是否轮播" class="el-col-12">
          <el-switch
            v-model="temp.isBanner"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <Tinymce ref="editor" v-model="temp.content" :height="300" :images-upload-url="config.action"></Tinymce>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="saveData">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, change, delAll, getInfo, save } from '@/api/blog'
import { getAll } from '@/api/category'
import { getAll as getTagAll } from '@/api/tag'
import waves from '@/directive/waves'
import { getArrByKey, difference } from '@/utils'
import openWindow from '@/utils/openWindow'
import tree from '@/utils/tree'
import myconfig from '@/config'
import UploadImage from '@/components/Upload/image'
import Tinymce from '@/components/TinymceEditor/tinymceEditor'

export default {
  name: 'Blog',
  components: { UploadImage, Tinymce },
  directives: {
    waves
  },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      selectedRows: null,
      listLoading: true,
      showSearch: false,
      listQuery: {
        page: 1,
        psize: 10,
        sort: 'id desc',
        title: '',
        cid: '-1',
        isDel: '-1',
        createTime: 'all',
        startTime: '',
        endTime: ''
      },
      buttonDisabled: true,
      deleting: false,
      dateTime: '',
      currentIndex: -1,
      hasDel: false,
      categoryList: null,
      // 添加/编辑
      dialogFormVisible: false,
      dialogTitle: '',
      btnLoading: false,
      temp: {
        id: 0,
        cid: '请选择',
        title: '',
        stitle: '',
        // keyword: '',
        synopsis: '',
        image: '',
        sort: '',
        url: '',
        source: '',
        displayTime: 0,
        status: 1,
        isDel: 0,
        isHot: 0,
        isBanner: 0,
        content: '',
        tags: []
      },
      config: {
        fileName: 'img',
        limit: 10,
        multiple: true,
        accept: 'image/*',
        action: myconfig.uploadUrl.img
      },
      rules: {
        cid: [{ required: true, message: '文章分类', trigger: 'change' }],
        title: [{ required: true, message: '文章标题', trigger: 'blur' }]
      },
      tags: [],
      displayTime: new Date().valueOf(),
      tagList: null
    }
  },
  computed: {
    allCategory() {
      return tree.listToTreeOne(this.categoryList)
    }
  },
  watch: {
    dateTime: function(val) {
      this.listQuery.startTime = val[0]
      this.listQuery.endTime = val[1]
    }
  },
  created() {
    this.getCategoryList()
    this.getTagList()
    this.fetchList()
  },
  methods: {
    // 获取文章list
    fetchList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 获取文章分类
    getCategoryList() {
      this.listLoading = true
      getAll().then(response => {
        this.categoryList = response.data
      })
    },
    // 获取文章标签
    getTagList() {
      this.listLoading = true
      getTagAll().then(response => {
        this.tagList = response.data
      })
    },
    // 添加
    handleAdd() {
      this.dialogFormVisible = true
      this.dialogTitle = '增加'
      this.initTemp()
    },
    // 点击页码
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchList()
    },
    // 永久删除
    handleDeleteAll() {
      const msg = '此操作将文章永久删除, 是否继续?'
      if (this.selectedRows.length > 0) {
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleting = true
          const ids = getArrByKey(this.selectedRows, 'id')
          const idstr = ids.join(',')
          delAll({ ids: idstr }).then(response => {
            if (response.status === 1) {
              this.fetchList()
              this.$message.success(response.msg)
            } else {
              this.$message.error(response.msg)
            }
            this.deleting = false
          }).catch((error) => {
            this.deleting = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$message.error('请选择要删除的数据')
      }
    },
    // 过滤刷新
    handleFilter() {
      this.listQuery.page = 1
      this.fetchList()
    },
    // 重置
    handleFilterClear() {
      this.listQuery = {
        page: 1,
        psize: 10,
        sort: 'id desc',
        title: '',
        cid: '-1',
        isDel: '-1',
        createTime: 'all',
        startTime: '',
        endTime: ''
      }
      this.dateTime = ''
      this.fetchList()
    },
    // 图片预览
    handleImg(img) {
      openWindow(img, '图片预览', '500', '400')
    },
    // 删除更改(回收站)
    handleModifyDelStatus(data, index) {
      this.list[index]['isDel'] = data.isDel
      change(data.id, 'isDel', data.isDel).then(response => {
      })
    },
    // 状态更改
    handleModifyStatus(data, index) {
      this.list[index]['status'] = data.status
      change(data.id, 'status', data.status).then(response => {
      })
    },
    // 多选
    handleSelectionChange(val) {
      this.buttonDisabled = !(val.length > 0)
      this.selectedRows = val
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.listQuery.psize = val
      this.fetchList()
    },
    // 更新
    handleUpdate(index, id) {
      this.listLoading = true
      this.dialogTitle = '编辑'
      getInfo(id).then(response => {
        this.temp = response.data
        this.tags = getArrByKey(this.temp.tags, 'id')
        this.displayTime = this.temp.displayTime === 0 ? this.temp.addTime * 1000 : this.temp.displayTime * 1000
        this.listLoading = false
        this.dialogFormVisible = true
      })
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    initTemp() {
      this.displayTime = new Date().valueOf()
      this.temp = {
        id: 0,
        cid: '请选择',
        title: '',
        stitle: '',
        // keyword: '',
        synopsis: '',
        image: '',
        sort: '',
        url: '',
        source: '',
        displayTime: 0,
        status: 1,
        isDel: 0,
        isHot: 0,
        isBanner: 0,
        content: '',
        tags: []
      }
      this.tags = []
    },
    saveData() {
      this.btnLoading = true
      this.temp.displayTime = this.displayTime / 1000
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (typeof (this.temp.image) === 'object') {
            this.temp.image = this.temp.image.join(',')
          }
          this.temp.tags = this.tags
          save(this.temp).then(response => {
            if (response.status === 1) {
              // 更新标签
              if (this.hasNewTag(this.temp)) {
                this.getTagList()
              }
              this.fetchList()
              this.dialogFormVisible = false
              this.$message.success(response.msg)
            } else {
              this.$message.error(response.msg)
            }
            this.btnLoading = false
          }).catch((error) => {
            this.btnLoading = false
          })
        }
      })
    },
    // 排序
    sortChange(data) {
      const { prop, order } = data
      if (prop !== null) {
        this.listQuery.sort = prop + ' ' + (order === 'ascending' ? 'asc' : 'desc')
        this.fetchList()
      }
    },
    // 判断是否有新增标签
    hasNewTag(temp) {
      const tagIds = getArrByKey(this.tagList, 'id')
      const tagDiff = difference(temp.tags, tagIds)
      return tagDiff.length > 0
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .text-red {
        color: red;
        cursor: pointer;
    }

    .text-green {
        color: green;
        cursor: pointer;
    }

    .item {
        margin-top: 10px;
        margin-right: 30px;

        .el-button {
            padding: 10px;
        }
    }

    .statusTitle {
        margin: 10px;
        display: inline-block;
        font-weight: 400;
    }

    /deep/ .el-dropdown-menu--medium .el-dropdown-menu__item {
        font-size: 12px;
    }

    .warning {
        text-align: center;

        .warning-icon {
            font-size: 50px;
            color: #e6a23c;
            margin-bottom: 10px;
        }

        .warning-content {
            font-size: 24px;
            font-weight: 600;
        }
    }

    .dialog-footer {
        text-align: center;
    }

    .keyword {
        display: block;
    }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
    /*图片上传*/
    /deep/ .image-uploader {
        .el-upload-list {
            .el-upload-list__item {
                width: 60px;
                height: 60px;
            }
        }
        .el-upload {
            width: 60px;
            height: 60px;
        }
    }
</style>
